package com.huiminpay.transaction.controller;

import com.alibaba.fastjson.JSON;
import com.huiminpay.agent.dto.PaymentResponseDTO;
import com.huiminpay.common.cache.util.AmountUtil;
import com.huiminpay.common.cache.util.EncryptUtil;
import com.huiminpay.common.cache.util.IPUtil;
import com.huiminpay.common.cache.util.ParseURLPairUtil;
import com.huiminpay.merchant.api.AppService;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.transaction.api.dto.PayOrderDTO;
import com.huiminpay.transaction.api.service.TransactionService;
import com.huiminpay.transaction.convert.PayOrderConvert;
import com.huiminpay.transaction.vo.OrderConfirmVO;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Controller
public class PayController {

    @Reference
    AppService appService;

    @Reference
    TransactionService transactionService;

    /**
     \* 支付入口
     \* @param ticket
     \* @param type
     \* @param request
     \* @return
     */
    @SneakyThrows
    @RequestMapping("/pay-entry/{ticket}")
    public String payEntry(@PathVariable("ticket") String ticket, HttpServletRequest request) {
        try {
            //将ticket的64还原
            String ticketStr = EncryptUtil.decodeUTF8StringBase64(ticket);
            //将ticket(json)转成对象
            PayOrderDTO order = JSON.parseObject(ticketStr, PayOrderDTO.class);
            //将对象转成Url格式
            BrowserType browserType = BrowserType.valueOfUserAgent(request.getHeader("user-agent"));
            switch (browserType){
                case ALIPAY://直接跳转收银台pay.html
                  return "forward:/pay-page?" + ParseURLPairUtil.parseURLPair(order);

                case WECHAT://获取授权码(待实现)
                    return "forward:/pay-page?" + ParseURLPairUtil.parseURLPair(order);
                default:
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(),e);
        }

        return "forward:/pay-page";
    }
    /**
     * 交易服务支付宝下单是提供给支付入口请求的支付宝付款接口，当用户用支付宝客户端扫描二维码进入确认支付页
     * 面，点击确认支付即将请求此接口。
     * 1、接口描述
     * 1）接收前端支付请求
     * 2）保存订单信息到惠民支付平台
     * 3）调用支付渠道代理服务请求支付宝下单接口
     * 4）将支付宝下单接口响应结果返回到前端，前端开始进行支付
     * @author glls
     * @param orderConfirmVO
     * @param request
     * @param response
     * @return void
     * @date 2021/3/4 21:16
     */
    @ApiOperation("支付宝门店下单付款")
    @PostMapping("/createAliPayOrder")
    public void createAlipayOrderForStore(OrderConfirmVO orderConfirmVO, HttpServletRequest request,
                                          HttpServletResponse response) throws Exception {
        // 支付宝的下单接口,前端订单确认页面，点击确认支付，请求进来
        PayOrderDTO payOrderDTO = PayOrderConvert.INSTANCE.vo2dto(orderConfirmVO);
        //应用id
        String appId = payOrderDTO.getAppId();

        // 设置merchantId 通过应用ID查询应用信息  然后再获取merchantId
        AppDTO appDTO = appService.queryAppByAppId(payOrderDTO.getAppId());

        payOrderDTO.setMerchantId(appDTO.getMerchantId());//商户id
        //将前端输入的 元转成分
        payOrderDTO.setTotalAmount(Integer.parseInt(AmountUtil.changeY2F(orderConfirmVO.getTotalAmount().toString())));
        //客户端ip
        payOrderDTO.setClientIp(IPUtil.getIpAddr(request));
        //保存订单，调用支付渠道代理服务的支付宝下单
        PaymentResponseDTO<String> paymentResponseDTO = transactionService.submitOrderByAli(payOrderDTO);
        //支付宝下单接口响应
        String content = paymentResponseDTO.getContent();
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(content);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }
}
